package com.example.activity;

import java.util.Iterator;
import java.util.Set;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.R;
import com.example.entity.Bookmark;
import com.example.entity.BookmarkList;
import com.example.entity.Const;
import com.example.entity.SelectMode;
import com.example.entity.ViewHolder;
import com.example.module.linker.FacebookLink;
import com.example.module.linker.KakaoLink;
import com.example.module.linker.TwitterLink;
import com.example.persistence.ImageActivity;
import com.example.persistence.MyApplication;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

public class BookmarkListActivity extends ImageActivity {
	private BookmarkList bookmarkList;
	private ListView listView;
	private DisplayImageOptions options;

	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bookmark);
        
        listView = (ListView) findViewById(R.id.listView);
        wrapContentView((FrameLayout) findViewById(R.id.container), listView);
        
		bookmarkList = application.getBookmarkList();
		
		listView.post(new Runnable() {
			@Override
			public void run() {
				listView.setAdapter(new ItemAdapter());
			}
		});
        
        options = new DisplayImageOptions.Builder()
			.showStubImage(R.drawable.icon_100)
			.showImageForEmptyUri(R.drawable.image_for_empty_url)
			.cacheInMemory()
			.cacheOnDisc()
			.displayer(new RoundedBitmapDisplayer(20))
			.build();
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Log.e("onItemClick", "position=" + position);
				
				if (selectMode == SelectMode.SINGLE)
					selectSingleItem(bookmarkList.get(position).getPath(), view);
				else if (selectMode == SelectMode.MULTIPLE)
					selectMultipleItem(bookmarkList.get(position).getPath(), view);
				else {
					Intent data = new Intent();
					data.putExtra("url", bookmarkList.get(position).getUrl());
					setResult(LOAD_URL_CODE, data);
					finish();
				}
			}
		});
    }
	
	class ItemAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return bookmarkList.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
//			Log.e("BookmarkListActivity getView", "position=" + position + " convertView=" + convertView);
			
			View view = convertView;
			if (convertView == null) {
				view = getLayoutInflater().inflate(R.layout.item_list, null);
				
				ViewHolder viewHolder = new ViewHolder();
				viewHolder.text = (TextView) view.findViewById(R.id.text);
				viewHolder.image = (ImageView) view.findViewById(R.id.image);
				viewHolder.checkOverlay = (FrameLayout) view.findViewById(R.id.checkOverlay);
				view.setTag(viewHolder);
			}
			
			
			ViewHolder viewHolder = (ViewHolder) view.getTag();
			viewHolder.text.setText(bookmarkList.get(position).getTitle());
			
			String key = bookmarkList.get(position).getPath();
			viewHolder.selected = isSelectedItem(key);
			viewHolder.checkOverlay.setVisibility(viewHolder.selected ? View.VISIBLE : View.GONE);
			
//			Log.e("BookmarkListActivity getView", "bookmark.selected=" + bookmarkList.get(position).selected);
				
			imageLoader.displayImage(bookmarkList.get(position).getPath(), viewHolder.image, options);

			return view;
		}
	}
	
	@Override
	protected void shareKakaoTalk(Set<String> selectedItem) {
		if (selectedItem == null || selectedItem.size() < 1)
			return;
		
		KakaoLink kakaoLink = KakaoLink.getLink(getApplicationContext());
		if (!kakaoLink.isAvailableIntent()) {
			alert("Not installed KakaoTalk.");			
			return;
		}
		
		MyApplication app = ((MyApplication) getApplication());
		Intent kakaoIntent = null;
		Iterator<String> keys = selectedItem.iterator();
		while (keys.hasNext()) {
			Bookmark bookmark = bookmarkList.get(keys.next());
			kakaoIntent = kakaoLink.getUrlLinkIntent( 
				bookmark.getUrl(), 
				bookmark.getTitle() + " 페이지 공유해요~", 
				app.getPackageName(), 
				app.getVersionName(),
				app.getAppName(),
				Const.DEFAULT_ENCODING);
			break;
		}
		
		deselectAllItems();
		startActivity(kakaoIntent);
	}

	@Override
	protected void shareTwitter(Set<String> selectedItem) {
		if (selectedItem == null || selectedItem.size() < 1)
			return;
		
		StringBuffer message = new StringBuffer();
		
		Iterator<String> keys = selectedItem.iterator();
		while (keys.hasNext()) {
			Bookmark bookmark = bookmarkList.get(keys.next());
			message.append(bookmark.getUrl()).append("\n").append(bookmark.getTitle()).append(" 페이지 공유해요~");
			break;
		}
		
		TwitterLink twitterLink = new TwitterLink(this);
		twitterLink.publish(message.toString());
	}
	
	@Override
	protected void shareFacebook(Set<String> selectedItem) {
		if (selectedItem == null || selectedItem.size() < 1)
			return;
		
		StringBuffer message = new StringBuffer();
		Iterator<String> keys = selectedItem.iterator();
		while (keys.hasNext()) {
			Bookmark bookmark = bookmarkList.get(keys.next());
			message.append(bookmark.getUrl()).append("\n").append(bookmark.getTitle()).append(" 페이지 공유해요~");
			break;
		}
		
		FacebookLink facebookLink = new FacebookLink(this);
		facebookLink.publish(message.toString());
	}
	
	@Override
	protected void doDelete(Set<String> selectedItem) {
		if (selectedItem == null || selectedItem.size() < 1)
			return;
		
		Iterator<String> keys = selectedItem.iterator();
		while (keys.hasNext()) {
			String key = keys.next();
			bookmarkList.removeItem(key);
			deleteLocalFile(key);
		}
		
		((ItemAdapter) listView.getAdapter()).notifyDataSetChanged();
	}
}
